import React from "react";
import {Menu} from "antd";
import {mapIndexSider} from "@/store/index/connect";
import {connect} from "react-redux";

const { SubMenu } = Menu;


class SiderMenu extends React.Component{

    componentDidMount() {
        this.props.getMenuData();
    }

    renderSubmenu = (item) => {
        return (
            <SubMenu key={item.key} title={
                <span>
                    <span>{item.title}</span>
                </span>
            }>
                {
                    item.routes.map(item1 => {
                        return this.renderMenuItem(item1)
                    })
                }
            </SubMenu>
        )
    }

    renderMenuItem = (item) => {
        return (
            <Menu.Item key={item.key}>{item.title}</Menu.Item>
        )
    }

    onOpenChange = openKeys => {
        // find() 方法返回通过测试（函数内判断）的数组的第一个元素的值。
        let {openKey, rootKeys, changeOpenKey} = this.props;
        const latestOpenKey = openKeys.find(key => openKey.indexOf(key) === -1);
        if (rootKeys.indexOf(latestOpenKey) === -1) {
            openKey = openKeys;
        } else {
            openKey = latestOpenKey ? [latestOpenKey] : [];
        }
        changeOpenKey(openKey);
    }

    onClick = ({key, item}) => {
        this.props.onClick(key, item.props.children);
    }

    render() {
        return (
            <Menu
                mode="inline"
                openKeys={this.props.openKey}
                onOpenChange={this.onOpenChange}
                onClick={this.onClick}
                className="menu"
            >
                {
                    Array.isArray(this.props.menuList) && this.props.menuList.map(item => {
                        if (Array.isArray(item.routes)) {
                            return this.renderSubmenu(item)
                        } else {
                            return this.renderMenuItem(item)
                        }
                    })
                }
            </Menu>
        );
    }

}
export default connect(mapIndexSider.mapStateToProps, mapIndexSider.mapDispatchToProps)(SiderMenu);
